﻿using Sharp.Infrastructure;
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure.Interception;
using System.Linq;

namespace Sharp.Domain.Repository.EF
{
    /// <inheritdoc />
    /// <summary>
    ///     平台数据访问上下文。
    /// </summary>
    public partial class SharpEntities : DbContext
    {
        #region 构造函数

        static SharpEntities()
        {
            
#if DEBUG
            DbInterception.Add(new IntercepterLogging());
#endif
#if MSSQL
            DbInterception.Add(new MsSqlNoLockInterceptor());
#endif
        }

        /// <summary>
        /// 平台数据访问上下文
        /// </summary>
        /// <param name="nameOrConnectionString"></param>
        public SharpEntities(string nameOrConnectionString) : base(nameOrConnectionString)
        {
            Configuration.AutoDetectChangesEnabled = true;
            Configuration.ProxyCreationEnabled = false;
            Configuration.LazyLoadingEnabled = false;
            Configuration.UseDatabaseNullSemantics = true;
        }
        #endregion


        #region OnModelCreating

        /// <summary>
        /// 重写ModelCreating
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            #region 公约

            modelBuilder.Properties<decimal>().Configure(x => x.HasPrecision(18, 4));
            modelBuilder.Properties<string>().Configure(x => x.HasMaxLength(50).IsUnicode(true));
            modelBuilder.Properties().Where(x => x.Name == "Id").Configure(x => x.HasColumnOrder(0));
            modelBuilder.Properties().Where(x => x.GetCustomAttributes(false).OfType<NonUnicodeAttribute>().Any()).Configure(c => c.IsUnicode(false));
            modelBuilder.Properties().Where(x => x.GetCustomAttributes(false).OfType<IsMaxLengthAttribute>().Any()).Configure(c => c.IsMaxLength());
            //modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            //modelBuilder.Conventions.Remove<OneToOneConstraintIntroductionConvention>();
            //modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
            #endregion

            //人为配置数据库架构
            if (System.Configuration.ConfigurationManager.AppSettings["DefaultSchema"].IsNotNullOrEmpty())
            {
                modelBuilder.HasDefaultSchema(System.Configuration.ConfigurationManager.AppSettings["DefaultSchema"]);
            }

        }

        #endregion
    }
}